#!/bin/bash
source tools/const.sh

ipenv="dev"

function getPortFromAppRootPath() {
    echo "$app_root_path" | grep -oE '[0-9]+'
}

if [ -h "$LINK_FILE" ]; then
    echo -e "$RED 已存在快捷方式 $RESET ${LINK_FILE}  ,指向文件 $GREEN" "$(readlink -f "${CONF_DIR}/${LINK_NAME}")" "$RESET"
    ls -all "${CONF_DIR}/${LINK_NAME}"
    exit 1
else
  echo "不存在配置文件文件,开始创建文件✅..."
  echo ""
  echo "--------------------本机ip hostname信息-----------------------------"
#  hostname -I | awk '{print $1}'
  ifconfig | grep 'inet ' | awk '{print $2}'
#  ip addr show | grep 'inet ' | awk '{print $2}'
  ip2=$(curl ifconfig.me)
  echo "当前ip, curl ifconfig.me = $ip2"
  # 判断 ip2是不是在变量里面 $testIps
  echo "当前目录是：$app_root_path"
  portFromRootPath=$(getPortFromAppRootPath)
  echo -e "根目录的文件夹名字包含的数字为 $GREEN $portFromRootPath $RESET"
  possibleConf=""
  num=$(echo "$testIps"|grep -c "$ip2")
  if [[ "$num" == 1 ]]; then
    possibleConf="test.${portFromRootPath}"
    echo -e "当前的ip在testip里面,$GREEN 当前环境极有可能是 test$RESET ,建议选择test相关的配置文件"
    ipenv="test"
  else
    # 判断是不是prod环境
    num=$(echo "$prodIps"|grep -c "$ip2")
    if [[ "$num" == 1 ]]; then
      possibleConf="prod.${portFromRootPath}"
      echo -e "当前的ip在testip里面,$GREEN 当前环境极有可能是 prod$RESET ,建议选择prod相关的配置文件"
      ipenv="prod"
    fi
  fi

  echo ""
  echo "-------------------------------------------------"
  echo ""
fi


#files=$(cd "$CONF_DIR" && find "." -type f -name "*.conf" ! -name "*.bak")
# shellcheck disable=SC2010
files=$(cd "$CONF_DIR" && ls |grep  "conf" |grep -v "\.bak")

# 检查是否有符合条件的文件
if [[ -z "$files" ]]; then
    echo -e "$BOLODRED 没有符合条件的文件！$RESET"
    exit 1
fi

# 打印文件列表和序号
# 输出带有加粗的深白色字体的标题
echo -e "${BOLD_WHITE}         path${RESET}"
i=0
while IFS= read -r file; do
  num2=$(echo "$file"|grep -c "$possibleConf")
  echo "possibleConf conf: $possibleConf"
  if [[ "$num2" == 1 && "$possibleConf" != "" ]];then
    export GREP_COLOR='32' # green
    echo -e "$GREEN ---------------------------------------- "
    echo -e " |   建议选择该文件                     |"
    echo -e " |$BOLDMAGENTA   $i:  $file                  |"
    echo -e "$GREEN ---------------------------------------- $RESET"
  else
    num=$(echo "$i:     $file"|grep -c "$ipenv")
    if [[ "$num" == 1 ]];then
      export GREP_COLOR='32' # green
      echo "      $i:  $file"|grep --color "$ipenv"
    else
      echo "      $i:  $file"
    fi
  fi
    i=$((i+1))
done <<< "$files"

# 读取用户输入的序号
# shellcheck disable=SC2162
read -p "请输入序号以选择文件创建快捷方式: " input

# 检查输入是否为合法的数字
re='^[0-9]+$'
if ! [[ $input =~ $re ]] || ((input < 0)) || ((input >= i)); then
    echo -e "$BOLODRED 无效的输入序号！$RESET"
    exit 1
fi

# 创建快捷方式
selected_file=$(echo "$files" | sed -n "$((input+1))p")

echo "selectFile: ${selected_file}"
echo "linkFile: ${LINK_NAME}"

cd "$CONF_DIR" && pwd && ln -s "${selected_file}" "${LINK_NAME}"

echo -e "已创建快捷方式 $GREEN${LINK_FILE}$RESET ,指向文件 $GREEN${CONF_DIR}/$selected_file$RESET"